package com.demo.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.demo.kits.CarFamilyKit;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.demo.vo.EventVO;
import com.demo.vo.ResultVO;
import com.jfinal.aop.ClearInterceptor;
import com.jfinal.aop.ClearLayer;
import com.jfinal.core.Controller;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.ehcache.CacheKit;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import javax.servlet.http.HttpSession;
import jodd.util.StringUtil;
import org.apache.log4j.Logger;

@ClearInterceptor(ClearLayer.ALL)
public class CarFamilyController extends Controller
{
  private static String AppId = "";
  private static String AppSecret = "";
  private static int cardate = 30;

  static { Properties r = PropertiesHelper.loadProperty("/weixin.properties");
    if (!r.isEmpty())
      try {
        AppId = r.getProperty("AppId");
        AppSecret = r.getProperty("AppSecret");
        cardate = Integer.parseInt(r.getProperty("cardate"));
      } catch (Exception e) {
        Logger.getLogger(Upload.class).error("无法读取参数", e);
      }
    else {
      Logger.getLogger(Upload.class).error("无法读取 weixin.properties");
    }
    PropKit.use("/a_little_config.txt");
  }

  public void index()
  {
    Map a = new HashMap();
    String code = getPara("code");
    String openid = "";
    if (StringUtil.isNotBlank(getCookie("openid"))) {
      openid = getCookie("openid");
    }
    else if (StringUtil.isNotBlank(code)) {
      openid = getopendid(code);
      setCookie("openid", openid, 864000);
    }
/*    else
    {
      redirect("https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx665766efbb169f39&redirect_uri=http://shmiandi.cn/wzcx&response_type=code&scope=snsapi_base&state=123#qgjtw_redirect");
      return;
    }*/

    a.put(openid, openid);
    if (StringUtil.isNotBlank(getPara("openid"))) {
      openid = getPara("openid");
    }
  /*  if (!StringUtil.isNotBlank(openid)) {
    	System.out.println("sssss");
        renderError(404, "/404error.html");
        return;
      }*/
//    if (!isSubscribe(openid)) {
//      renderError(404, "/404error.html");
//      return;
//    }

    String args = getPara("args");
    List carlist = new ArrayList();
    List car = new ArrayList();
    if (StringUtil.isNotBlank(openid)) {
      car = Db.find("select  *  from t_car where openid='" + openid + "'");
    }

    if (StringUtil.isNotBlank(args)) {
      carlist = Db.find("select * from t_car where id=" + args);
    }

    List _list = new ArrayList();
    List _lists = new ArrayList();
    _list = (List)CacheKit.get("province", "province");
    if (_list == null)
    {
      _list = Db.find("select A.id,A.province_code,A.province from t_city A join (select distinct(provincename) provname,support from t_cities) B on A.province=B.provname where B.support=1");
      CacheKit.put("province", "province", _list);
    }
    _lists = (List)CacheKit.get("city", "city");
    if (_lists == null)
    {
      _lists = Db.find("select  B.city, A.cityname as city_name,B.city_code,B.abbr, A.provincename,A.enginenumlen>0 as engine,  A.enginenumlen as engineno,A.framenumlen>0 as classa,  A.framenumlen as classno,  A.support,  A.firstletter from t_cities A left join t_xian B ON A.cityname=B.city_name");

      CacheKit.put("city", "city", _lists);
    }

    if (StringUtil.isNotBlank(getPara("openid"))) {
      setAttr("objectlist", 
        Car.dao.find("select * from t_car where openid=? ", new Object[] { openid }));
      setAttr("province", _list);
      setAttr("openid", openid);
      setAttr("city", _lists);
      setAttr("carlist", carlist);
      setAttr("args", args);
      renderFreeMarker("/vehicle-action.html");
    }
    else if (car.size() > 0) {
      setAttr("openid", openid);
      setAttr("objectlist", Car.dao.find(
        "select * from t_car where openid=? ", new Object[] { openid }));
      List list = 
        Db.find(" SELECT SUM( a.fen ) AS unhandled_violation_point,  SUM( a.money ) AS unhandled_violation_fine, COUNT( * ) AS unhandled_count, UPPER( a.hphm) AS vehicle_id FROM t_eventlist a, t_car b   WHERE a.hphm = b.hphm AND b.openid ='" + 
        openid + "'  GROUP BY a.hphm");

      if (StringUtil.isNotBlank(getPara("add"))) {
        if (getPara("add").endsWith("add")) {
          setAttr("province", _list);
          setAttr("openid", openid);
          setAttr("city", _lists);
          setAttr("carlist", carlist);
          renderFreeMarker("/vehicle-action.html");
        }
      } else {
        setAttr("openid", openid);
        setAttr("fenz", list);
        renderFreeMarker("/vehicle-list.html");
      }
    } else {
      setAttr("province", _list);
      setAttr("openid", openid);
      setAttr("city", _lists);
      setAttr("carlist", carlist);
      setAttr("args", args);
      renderFreeMarker("/vehicle-action.html");
    }
  }

  public void violations()
  {
    String id = getPara("args");
    List carlist = Db.find("select * from t_car where id =?", new Object[] { id });
    setAttr("carlist", carlist);
    setAttr("args", id);
    renderFreeMarker("/vehicle-violations.html");
  }

  public void resultListJson() throws UnsupportedEncodingException
  {
    String args = getPara("args");

    String city = "";
    String hphm = "";
    String hpzl = "02";
    String engineno = "";
    String classno = "";
    String registno = "";

    String cxrq = "";
    Date date = new Date();
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
    cxrq = sdf.format(date);

    List carlist = Db.find("select * from t_car where id =?", new Object[] { args });

    String city_name = "";
    if (carlist.size() > 0) {
      hphm = ((Record)carlist.get(0)).getStr("hphm");
      city = ((Record)carlist.get(0)).getStr("city_code");
      engineno = ((Record)carlist.get(0)).getStr("engine_num");
      classno = ((Record)carlist.get(0)).getStr("body_num");
      registno = ((Record)carlist.get(0)).getStr("license_number");

      city_name = ((Record)carlist.get(0)).getStr("city_name");
    }

    String rq = "";

    List datelist = 
      Db.find("select * from t_querylog where hphm ='" + hphm + 
      "' order by id desc ");
    List datlist = 
      Db.find("select * from t_eventlist  where hphm ='" + hphm + 
      "' order by id desc ");

    int j = 0;
    if (datelist.size() > 0) {
      rq = ((Record)datelist.get(0)).get("cxrq").toString();

      j = cutTwoDateToDay(rq, cxrq);
    }

    if (((datelist.size() > 0) && (j > cardate)) || 
      ((datlist.size() == 0) && (datelist.size() > 0)) || (
      (datlist.size() == 0) && (datelist.size() == 0))) {
      Map params = new HashMap();
      params.put("platform_id", "17");
      params.put("cityid", CarFamilyKit.queryCityIdByName(city_name));
      params.put("cip", PropKit.get("cip", "122.114.123.94"));
      params.put("platenum", URLEncoder.encode(hphm, "utf-8"));
      params.put("enginenumber", engineno);
      params.put("framenumber", classno);

      params.put("lng", null);
      params.put("lat", null);
      System.out.println("CarFamilyKit.queryViolations(params)"+CarFamilyKit.queryViolations(params));
      JSONObject jsonTexts = CarFamilyKit.convertToOld(CarFamilyKit.queryViolations(params));
      String errorcode = "";
      if (StringUtil.isNotBlank(jsonTexts.getString("error_code"))) {
        errorcode = jsonTexts.getString("error_code");
      }

      if (errorcode.equals("0"))
      {
        Record log = new Record();
        log.set("hphm", hphm);
        log.set("cxrq", cxrq);

        Db.save("t_querylog", log);

        String resultJsonText = jsonTexts.getString("result");

        ResultVO result = (ResultVO)JSON.parseObject(resultJsonText, 
          ResultVO.class);
        if (result != null) {
			List<EventVO> events = result.getLists();

          if (events != null) {
            for (EventVO each : events) {
              Record xx = new Record();
              xx.set("date", each.getDate());
              xx.set("area", each.getArea());
              xx.set("act", each.getAct());
              xx.set("code", each.getCode());
              xx.set("fen", each.getFen());
              xx.set("money", each.getMoney());
              xx.set("handled", each.getHandled());
              xx.set("payno", each.getPayno());
              xx.set("longitude", each.getLongitude());
              xx.set("latitude", each.getLatitude());
              xx.set("latitude", each.getLatitude());
              xx.set("hphm", hphm);
              xx.set("cxrq", cxrq);

              List list = Db.find("select * from t_eventlist where date ='" + 
                each.getDate() + 
                "'   and hphm='" + 
                hphm + "' ");
              if ((list.size() > 0) && (list != null)) {
                xx.set("id", ((Record)list.get(0)).get("id"));
                Db.update("t_eventlist", xx);
              } else {
                xx.remove("id");
                Db.save("t_eventlist", xx);
              }
            }
          }
        }
      }
    }

    resultJson(hphm, city);
  }

  public void vehicle_list()
  {
    String openid = getPara("openid");
    setAttr("objectlist", 
      Car.dao.find("select * from t_car where openid=?", new Object[] { openid }));
    setAttr("openid", openid);
    renderFreeMarker("/vehicle-list.html");
  }

  public void listJson() {
    String openid = getPara("openid");
    ArrayList List = new ArrayList();
    List<Record> list = 
      Db.find("  select sum(fen) as unhandled_violation_point,sum(money)   as unhandled_violation_fine , count(*)  as  unhandled_count,hphm as vehicle_id from t_eventlist where hphm in (select hphm from t_car where openid = '" + 
      openid + "')  group by hphm");
    if (list.size() > 0) {
      for (Record n : list) {
        List.add(n);
      }
    }

	List<Record> car = new ArrayList<Record>();
    if (StringUtil.isNotBlank(openid)) {
      car = Db.find("select  '0' as unhandled_violation_point  , '0'  as  unhandled_violation_fine ,'0' as unhandled_count,hphm as vehicle_id    from t_car where  hphm not in (select hphm from  t_eventlist  group by hphm) and openid='" + 
        openid + "'");
      for (Record n : car) {
        List.add(n);
      }
    }

    renderJson(List);
  }

  public void queryjson()
  {
    String openid = getPara("openid");
    String action = getPara("action");
    String license_num = getPara("license_num");
    String license_number = getPara("license_number");
    String body_num = getPara("body_num");
    String engine_num = getPara("engine_num");
    String city_name = getPara("city_name");
    String city_code = getPara("city_code");
    Car temp = (Car)Car.dao.findFirst("select * from t_car where hphm =  '" + 
      license_num + "'   and openid  = '" + openid + "'");

    String args = getPara("args");
    if (action.equals("add")) {
      if (temp == null) {
        Car car = new Car();

        ((Car)((Car)((Car)((Car)((Car)car.set("hphm", license_num))
          .set("license_number", license_number))
          .set("body_num", body_num))
          .set("engine_num", engine_num))
          .set("city_name", city_name))
          .set("city_code", city_code);
        car.set("openid", openid);
        boolean flag = car.save();
        if (flag) {
          String content = "{\"msg\":\"ok\",\"id\":\"args=" + 
            car.getInt("id") + "\"}";
          JSONObject jsonText = (JSONObject)JSON.parse(content);
          renderJson(jsonText);
        }
      }
      else {
        String content = "{\"msg\":\"ok\",\"id\":\"args=" + 
          temp.get("id").toString() + "\"}";
        JSONObject jsonText = (JSONObject)JSON.parse(content);
        renderJson(jsonText);
      }
    } else {
      Car car = new Car();

      ((Car)((Car)((Car)((Car)((Car)((Car)car.set("hphm", license_num)).set("license_number", license_number))
        .set("body_num", body_num)).set("engine_num", engine_num))
        .set("city_name", city_name)).set("city_code", city_code))
        .set("id", Integer.valueOf(Integer.parseInt(args)));
      boolean flag = car.update();
      if (flag) {
        String content = "{\"msg\":\"ok\",\"id\":\"args=" + args + 
          "\"}";
        JSONObject jsonText = (JSONObject)JSON.parse(content);
        renderJson(jsonText);
      } else {
        String content = "{\"msg\":\"no\",\"id\":\"args=" + args + 
          "\"}";
        JSONObject jsonText = (JSONObject)JSON.parse(content);
        renderJson(jsonText);
      }
    }
  }

  public void delete()
  {
    String action = getPara("action", "");
    if (action.equals("del")) {
      String args = getPara("args");
      boolean flag = Car.dao.deleteById(args);
      if (flag) {
        String content = "{\"msg\":\"ok\"}";
        JSONObject jsonText = (JSONObject)JSON.parse(content);
        renderJson(jsonText);
        return;
      }
    }
  }

  public static int cutTwoDateToDay(String a, String b)
  {
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Calendar calendar = Calendar.getInstance();
    int theday = 0;
    try {
      Date beginDate = format.parse(a);
      Date endDate = format.parse(b);

      calendar.setTime(beginDate);
      long begin = calendar.getTimeInMillis();
      calendar.setTime(endDate);
      long end = calendar.getTimeInMillis();

      theday = (int)((end - begin) / 86400000L);
    } catch (ParseException e) {
      e.printStackTrace();
    }
    return theday;
  }

  public void resultJson(String hphm, String city) {
    int total_fine = 0;
    int total_point = 0;
    List<Record> list = 
      Db.find("select  id as vehicle_id,area as violation_address ,act as violation_type ,fen as violation_points ,money as violation_fine , handled as violation_status_text , longitude as  violation_longitude , latitude as  violation_latitude  ,code  as violation_count ,  UNIX_TIMESTAMP(date) as violation_time  from  t_eventlist where hphm ='" + 
      hphm + 
      "'    order by date desc");
    for (Record n : list) {
      total_fine += Integer.parseInt(n.get("violation_fine").toString());

      total_point = total_point + 
        Integer.parseInt(n.get("violation_points")
        .toString());
    }
    HashMap map = new HashMap();
    if (list.size() > 0) {
      map.put("stat", "ok");
      map.put("data", list);
      map.put("total_count", Integer.valueOf(list.size()));
      map.put("message", null);
      map.put("total_fine", Integer.valueOf(total_fine));
      map.put("total_point", Integer.valueOf(total_point));
      map.put("page_size", "10");
    } else {
      map.put("stat", "no");
      map.put("data", list);
      map.put("total_count", Integer.valueOf(list.size()));
      map.put("message", " 未查询到违章记录 请保持良好驾驶习惯");
      map.put("total_fine", Integer.valueOf(total_fine));
      map.put("total_point", Integer.valueOf(total_point));
      map.put("page_size", "0");
    }
    renderJson(map);
  }

  public String getopendid(String code)
  {
    String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=AppId&secret=AppSecret&code=CODE&grant_type=authorization_code";
    url = url.replace("AppId", AppId).replace("AppSecret", AppSecret)
      .replace("CODE", code);
    String jsonResult = HttpKit.get(url);
    JSONObject jsonTexts = (JSONObject)JSON.parse(jsonResult);
    String openid = "";
	if (StringKit.notNull(jsonTexts.get("openid"))) {
      openid = jsonTexts.get("openid").toString();
    }
    return openid;
  }

  public final boolean isSubscribe(String openid)
  {
    HttpSession session = getSession();

    String accessToken = (String)session.getAttribute("access_token");
    if (StringUtil.isBlank(accessToken)) {
      String getAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + AppId + "&secret=" + AppSecret;
      String atJsonStr = HttpKit.get(getAccessTokenUrl);
      accessToken = JSON.parseObject(atJsonStr).getString("access_token");
      session.setAttribute("access_token", accessToken);
    }
    String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken + "&openid=" + openid + "&lang=zh_CN";
    JSONObject jsonRes = JSON.parseObject(HttpKit.get(url));
    return 1 == jsonRes.getIntValue("subscribe");
  }
}